package org.andao.core.utils;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 图片压缩工具.
 * 
 * @author Marco.hu(hzg139@163.com)
 */
public final class ThumbnailsHelper {
	
	//所略图像
	private static BufferedImage resize(BufferedImage source, int targetW,int targetH) {		
		int type = source.getType();
		BufferedImage target = null;
		
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		
		if (sx > sy) {//等比例缩放
			sx = sy;
			targetW = (int) (sx * source.getWidth());
		} else {
			sy = sx;
			targetH = (int) (sy * source.getHeight());
		}
		if (type == BufferedImage.TYPE_CUSTOM) { // handmade
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW,targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else{
			target = new BufferedImage(targetW, targetH, type);
		}
		
		Graphics2D g = target.createGraphics();
		// smoother than exlax:
		g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}
	
	/**
	 * 生成缩略图,支持等比例缩放.
	 * @param srcFilePath 源文件路径
	 * @param distFilePath 目标文件路径
	 * @param width 生成的with
	 * @param hight 生成的height
	 * @throws IOException
	 */
	public static void createThumbnail(String srcFilePath, String distFilePath,	int width, int hight) throws IOException{		
		String imgType = srcFilePath.substring(srcFilePath.lastIndexOf(".") + 1).toLowerCase();;				
		File saveFile = new File(distFilePath);
		File fromFile = new File(srcFilePath);
		BufferedImage srcImage = ImageIO.read(fromFile);
		if (width > 0 || hight > 0) {
			srcImage = resize(srcImage, width, hight);
		}
		ImageIO.write(srcImage, imgType, saveFile);
	}

}
